<?php
/**
 * Created by PhpStorm.
 * User: pf
 * Date: 2017/12/18
 * Time: 15:09
 */

namespace App\Repositories;


use App\Exceptions\WechatException;
use App\Member;
use Illuminate\Support\Facades\Log;
use Psy\Exception\ErrorException;

class PacketRepository
{//红包
    protected $wechat;
    protected $luckyMoney;
    protected $merchantPay;

    public function __construct()
    {
        $this->wechat = app('wechat');
        $this->luckyMoney = $this->wechat->lucky_money;
        $this->merchantPay=$this->wechat->merchant_pay;;
    }
    public function recharge($member,$money){
        //  $this->sendNormalPacket($member,$money,'提现红包','提现红包','');
         return   $this->merchantPay($member,$money);
    }

    //红包付款
    public function sendNormalPacket($member,$money,$send_name,$wishing,$act_name,$remark)
    {
        $luckyMoneyData = [
            'mch_billno' => 'xy123456',
            'send_name' => '测试红包',
            're_openid' =>$member->openid,
            'total_num' => 1,  //普通红包固定为1，裂变红包不小于3
            'total_amount' => $money,  //单位为分，普通红包不小于100，裂变红包不小于300
            'wishing' => '祝福语',
        //    'client_ip' => '192.168.0.1',  //可不传，不传则由 SDK 取当前客户端 IP
            'act_name' => '测试活动',
            'remark' => '测试备注',
            // ...
        ];
        return  $result = $this->luckyMoney->send($luckyMoneyData, \EasyWeChat\Payment\LuckyMoney\API::TYPE_NORMAL);
    }
    public function merchantPay($member,$money,$desc='提现'){
        $merchantPayData = [
            'partner_trade_no' => str_random(16), //随机字符串作为订单号，跟红包和支付一个概念。
            'openid' => $member->openid, //收款人的openid
            'check_name' => 'NO_CHECK',  //文档中有三种校验实名的方法 NO_CHECK OPTION_CHECK FORCE_CHECK
            're_user_name'=>'张三',     //OPTION_CHECK FORCE_CHECK 校验实名的时候必须提交
            'amount' => (int)($money*100),  //单位为分
            'desc' => $desc,
           'spbill_create_ip' => '192.168.0.1',  //发起交易的IP地址
        ];

       $result = $this->merchantPay->send($merchantPayData);

        if(isset($result['result_code'])&&$result['result_code']=="SUCCESS"){
            return true;
        }
        throw new WechatException(200,$result['return_msg']);
    }


}